<template>
  <!-- 侧边导航 -->
  <div class="menu">
    <div class="search-box">
      <van-search icon="scan" size="small" class="menu-search" shape="round" v-model="keyword">
      </van-search>
      <button size="small" class="search-bt" type="success" @click="handleSearch(keyword)">搜索</button>
    </div>
    <div class="content">
      <div class="nav-side">
        <van-sidebar v-model="active">
          <van-sidebar-item @click="changeMenu(item.id)" v-for="item in cateslist" :key="item.id" :title="item.title" />
        </van-sidebar>
      </div>
      <div class="right">
        <div class="container">
          <CatesGoods :catesGoods="state.catesGoods" :title="title" />
        </div>
      </div>
    </div>
  </div>
  <TabBar :cart_badge="cartCount" />
</template>
  
<script setup>
import TabBar from '../components/Tabbar.vue'
import CatesGoods from '../components/CatesGoods.vue';
import axios from '../utils/axios.js'
import { useRouter } from 'vue-router';
import { useStore } from 'vuex'
import { onMounted, computed, ref, reactive } from 'vue';

const router = useRouter()
const store = useStore()
const cateslist = ref([])
const active = ref(0)
const title = ref('')
// 搜索关键词
const keyword = ref('')
// 跳转至搜索页
const handleSearch = (keyword) => {
    router.push({ path: 'search', query: { search: keyword }});
    console.log(keyword)
}
// cartCount用以承接全局的当前加购商品总数
const cartCount = computed(() => store.state.cartCount)
// 将 home 页点击菜品分类时通过路由传来的 params.id 绑定给侧边栏激活的类别
// active.value = router.currentRoute.value.params.id - 1
active.value = router.currentRoute.value.query.id - 1
const state = reactive({
  catesGoods: []
})
// 边栏导航菜单切换类目事件，传入的id用以区分菜品类别
const changeMenu = (id) => {
  axios.post('/list', { id: id }).then((res) => {
    state.catesGoods = res.data
  })
  title.value = cateslist.value[id - 1].title
  // router.push(`/menu/${id}`)
  router.push({path: 'menu', query: id})
}
onMounted(async () => {
  // console.log(router.currentRoute.value.query)
  axios.get('/catelist').then((res) => {
    cateslist.value = res.data
    // title.value = res.data[router.currentRoute.value.params.id - 1].title
    title.value = res.data[router.currentRoute.value.query.id - 1].title
  })
  // axios.post('/list', { id: Number(router.currentRoute.value.params.id) }).then((res) => {
  //   state.catesGoods = res.data
  // })
  axios.post('/list', { id: Number(router.currentRoute.value.query.id) }).then((res) => {
    state.catesGoods = res.data
  })
  store.dispatch('fetchCartCount')
})
</script>
  
<style lang="less" scoped>
.content {
  display: flex;
  width: 100%;
}

.nav-side {
  width: 20%;
}

.right {
  /* background-color: aqua; */
  width: 80%;
  margin-bottom: 2rem;
}



.container {
  /* background: #ab8484; */
  margin-left: 0.2rem;
  width: 100%;
  /* height: 100%; */
}
</style>